//
//  CalendarView.m
//  DemoCalendar
//
//  Created by Linh NGUYEN on 1/15/13.
//  Copyright (c) 2013 Mobioneer Ltd. All rights reserved.
//

#import "CalendarView.h"

@interface CalendarView() {
    BOOL flag;
    BOOL viewMode;
    NSDate* today;
    NSDate* currentHighlightDate;
    NSInteger monthMode;
    NSDate* dateMode;
    NSDate* firstDateofMonth;
    
    NSString *yearString;
    NSInteger year, weekDay, month;
    int DAY;
    float x, y, width,height;
    NSString *date;
}

@end

@implementation CalendarView

@synthesize strCalDate;
@synthesize strShoeInfoDate;

- (void)layoutSubviews
{
    _dayNames = [[NSArray alloc] initWithObjects: @"Sun", @"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", nil];
    _monthNames = [[NSArray alloc] initWithObjects: @"January", @"February", @"March", @"April", @"May", @"June", @"July", @"August", @"September", @"October", @"November", @"December", nil];
    
    cal = [NSCalendar currentCalendar];
    today = [NSDate date];
    
    compA =[cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
    
    firstDateofMonth=[today dateByAddingTimeInterval:([compA day]-1)*(-24*60*60)];
    
    compA =[cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:firstDateofMonth];
    
    today = firstDateofMonth;
    
    compA = [cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
    [compA setMonth:([compA month])];
    [self drawMonth];
}

//Remove view and create new view
-(void)removeView
{
	for (UIView *v in _contentView.subviews)
	{
		if ([v isKindOfClass:[UIButton class]])
			[v removeFromSuperview];
	}
}

//show next month calendar when next button press
- (IBAction)nextMonth:(id)sender
{
	[self removeView];
	cal = [NSCalendar currentCalendar];
	compA = [cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
	[compA setMonth:([compA month]+1)];// it will increase month by 1 for next month;
	monthMode = [compA month];
	[self drawMonth];
	
}

//show Previous month calendar when previous button press
-(IBAction)preMonth:(id)sender
{
	[self removeView];
	cal = [NSCalendar currentCalendar];
	compA = [cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
	[compA setMonth:([compA month]-1)];// it will decrease month by 1 for previous month;
	monthMode = [compA month];
	[self drawMonth];
	
}

// return true value of current date, current month
-(BOOL)isCurrentDate
{
	cal = [NSCalendar currentCalendar];
	currentHighlightDate = [NSDate date];
	currentHighLightDateComp = [cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit)
										fromDate:currentHighlightDate];
	currentDay = [currentHighLightDateComp day];
	currentMonth = [currentHighLightDateComp month];
	return YES;
}

// set the x and y coordinate and width and height of buttons in Portrait and LandScape
-(void)setPosition
{
	if(x==276)
    {
        y+=height;
        x=0;
    }
    else
    {
        x+=width;
    }
}

//create calender Portrait View
-(void)drawMonth
{
	flag = [self isCurrentDate];
	today = [cal dateFromComponents:compA];
	compA = [cal components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
	
	weekDay = [compA weekday];
	month = [compA month];
	year = [compA year];
	DAY = [compA day];
    
	
	NSString* _monthString = [_monthNames objectAtIndex:([compA month]-1)];
	NSString *_yearString = [NSString stringWithFormat:@" %d",[compA year]];
	_lblMonth.text = [_monthString stringByAppendingString:_yearString];
	[self showMode];
}

// It show the view according to LandScape and Portrait
-(void)showMode
{
	int i,day;
    [self removeView];
    x=(46*(weekDay-1)),y=38;
    width=46,height=46;
    int numberDayBefore = weekDay - 1;
    int lastDay;
    int lastMonth = month - 1;
    int lastYear = year;
    if( month == 1)
        lastYear = year - 1;
    
    if(lastMonth == 0)
        lastMonth = 12;
    day = [self numberDayInMonth:month Year:year];
    lastDay = [self numberDayInMonth:lastMonth Year:lastYear];
	lastDay -= numberDayBefore;
    
	for(i=1;i<=day;i++){
		if (flag && (currentDay == i) && (currentMonth == month) )
		{
			buttonImage.image = [UIImage imageNamed:@"choiceDay.png"];
			btnDay = [UIButton buttonWithType:UIButtonTypeCustom];
			btnDay.frame = CGRectMake(x,y,width,height);
			[btnDay addTarget:self action:@selector(dayClicked:) forControlEvents:UIControlEventTouchUpInside];
			[btnDay setBackgroundImage:[UIImage imageNamed:@"choiceDay.png"] forState:UIControlStateNormal];
			[btnDay setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
			[_contentView addSubview:btnDay];
			[self setPosition];
			
			
		}
		else if(DAY == i && (currentMonth != month))
		{
			buttonImage.image = [UIImage imageNamed:@"choiceDay.png"];
			btnDay = [UIButton buttonWithType:UIButtonTypeCustom];
			btnDay.frame = CGRectMake(x,y,width,height);
			[btnDay addTarget:self action:@selector(dayClicked:) forControlEvents:UIControlEventTouchUpInside];
			[btnDay setBackgroundImage:[UIImage imageNamed:@"choiceDay.png"] forState:UIControlStateNormal];
			[btnDay setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
			[_contentView addSubview:btnDay];
			[self setPosition];
			
		}
		else
		{
			
			buttonImage.image = [UIImage imageNamed:@"nomalDay.png"];
			btnDay = [UIButton buttonWithType:UIButtonTypeCustom];
			btnDay.frame = CGRectMake(x,y,width,height);
			[btnDay addTarget:self action:@selector(dayClicked:) forControlEvents:UIControlEventTouchUpInside];
			[btnDay setBackgroundImage:[UIImage imageNamed:@"nomalDay.png"] forState:UIControlStateNormal];
			[btnDay setBackgroundImage:[UIImage imageNamed:@"choiceDay.png"] forState:UIControlStateHighlighted];
			[btnDay setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
			[btnDay setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
			[_contentView addSubview:btnDay];
			[self setPosition];
			
		}
	}
    int numberDayAfter = 7 - ((int)x / 46) + (5 - (int)((y - 38)/46))*7;
    
    for( i = 0; i < numberDayAfter; i++)
    {
        buttonImage.image = [UIImage imageNamed:@"nomalDay.png"];
        btnDay = [UIButton buttonWithType:UIButtonTypeCustom];
        btnDay.frame = CGRectMake(x,y,width,height);
        [btnDay addTarget:self action:@selector(dayClicked:) forControlEvents:UIControlEventTouchUpInside];
        [btnDay setBackgroundImage:[UIImage imageNamed:@"nomalDay.png"] forState:UIControlStateNormal];
        [btnDay setBackgroundImage:[UIImage imageNamed:@"choiceDay.png"] forState:UIControlStateHighlighted];
        [btnDay setTitle:[NSString stringWithFormat:@"%d",i + 1] forState:UIControlStateNormal];
        [btnDay setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_contentView addSubview:btnDay];
        [self setPosition];
    }
    x = 0;
    y = 38;
    for( i = 0; i < numberDayBefore; i++)
    {
        buttonImage.image = [UIImage imageNamed:@"nomalDay.png"];
        btnDay = [UIButton buttonWithType:UIButtonTypeCustom];
        btnDay.frame = CGRectMake(x,y,width,height);
        [btnDay addTarget:self action:@selector(dayClicked:) forControlEvents:UIControlEventTouchUpInside];
        [btnDay setBackgroundImage:[UIImage imageNamed:@"nomalDay.png"] forState:UIControlStateNormal];
        [btnDay setBackgroundImage:[UIImage imageNamed:@"choiceDay.png"] forState:UIControlStateHighlighted];
        [btnDay setTitle:[NSString stringWithFormat:@"%d",lastDay + i + 1] forState:UIControlStateNormal];
        [btnDay setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_contentView addSubview:btnDay];
        [self setPosition];
    }
    
}
- (int)numberDayInMonth:(int)Tmonth Year:(int)Tyear
{
    if(Tmonth==1 || Tmonth==3 || Tmonth==5 || Tmonth==7 || Tmonth==8 || Tmonth==10 || Tmonth==12)
	{
		return 31;
	}
	else if(Tmonth==4 || Tmonth==6 || Tmonth==9 || Tmonth==11){
		return 30;
	}
	else if(Tmonth==2)
	{
		if((Tyear%4==0 && Tyear%100!=0)||(Tyear%400==0))
		{
			return 29;
		}
		else
		{
			return 28;
		}
	}
    return 0;
}
- (void)dayClicked:(id)sender
{
	btnDay = sender;
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:[[btnDay currentTitle] integerValue] + 1];
    [components setMonth:month];
    [components setYear:year];
    NSDate *currentDate = [cal dateFromComponents:components];
    [self.delegate calendarView:self didSelectDay:currentDate];	
}

@end
